package com.example.juc.count_down_latch;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试 CountDownLatch 在线程池使用时是否可以
 * 1、newCachedThreadPool创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程。
 * <p>
 * 2、newFixedThreadPool 创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。
 * <p>
 * 3、newScheduledThreadPool 创建一个定长线程池，支持定时及周期性任务执行。
 * <p>
 * 4、newSingleThreadExecutor 创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
 */
@Slf4j
public class Test1 {
    static ExecutorService threadPool = Executors.newFixedThreadPool(2);

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latchmain = new CountDownLatch(2);
        new Thread(() -> {
            CountDownLatch latch = new CountDownLatch(20);
            for (int i = 0; i < 20; i++) {
                int finalI = i;
                threadPool.submit(() -> {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.info("sout" + finalI);
                    latch.countDown();
                });
            }
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("----------------end  1-------------");
            latchmain.countDown();
        },"t1").start();


        new Thread(() -> {
            CountDownLatch latch2 = new CountDownLatch(20);
            for (int i = 0; i < 20; i++) {
                int finalI = i;
                threadPool.submit(() -> {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.info("lr!!!" + finalI);
                    latch2.countDown();
                });
            }
            try {
                latch2.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("----------------end 2!!!!!!!!!!!!-------------");
            latchmain.countDown();
        },"t2").start();

        latchmain.await();
        System.out.println("end main");
        threadPool.shutdown();
    }
}
